// This script generates a .vscodeignore file based on the package-lock.json.

const fs = require('fs');
const path = require('path');

// --- Configuration ---
// Add the names of the packages you need to ship in node_modules.
// For example:
// const rootPackages = ['sharp', 'pdf-parse', 'pdfjs-dist'];
// pdf-parse and pdfjs-dist are already manually handled.
const rootPackages = ['sharp'];
// -------------------

console.log('Generating .vscodeignore from package-lock.json...');

try {
  const lockfilePath = path.join(__dirname, 'package-lock.json');
  if (!fs.existsSync(lockfilePath)) {
    throw new Error('package-lock.json not found. Please run "npm install" first.');
  }

  const lockfileContent = fs.readFileSync(lockfilePath, 'utf-8');
  const lockfile = JSON.parse(lockfileContent);

  // Ensure we are working with a v2/v3 lockfile which has the 'packages' map
  if (!lockfile.packages) {
    throw new Error(
      'This script requires a lockfile version 2 or 3 (npm v7+). Please update npm or adjust the script.',
    );
  }

  const allDependencies = new Set(['@img']);
  const ignoredDependencies = ['@img', ...rootPackages]; // Add any other dependencies you want to ignore
  const queue = [...rootPackages]; // Start with our root packages

  // Add root packages to the set initially
  rootPackages.forEach((pkg) => allDependencies.add(pkg));

  while (queue.length > 0) {
    const currentPackage = queue.shift();
    const packageKey = `node_modules/${currentPackage}`;

    const packageInfo = lockfile.packages[packageKey];

    if (packageInfo) {
      // Combine production and optional dependencies
      const dependencies = {
        ...(packageInfo.dependencies || {}),
        ...(packageInfo.optionalDependencies || {}),
      };

      for (const depName in dependencies) {
        if (!allDependencies.has(depName)) {
          allDependencies.add(depName);
          queue.push(depName);
        }
      }
    }
  }

  console.log(`Found ${allDependencies.size} unique dependencies.`);

  const ignoreHeader = `# This file is auto-generated by vscodeignore.js. DO NOT EDIT MANUALLY.
# It ensures that only necessary production dependencies are packaged with the extension.

.vscode/**
.vscode-test/**
out/**
packages/**
python/**
examples/**
test-fixtures/**
.gitignore
.yarnrc
vsc-extension-quickstart.md
**/tsconfig.json
**/.eslintrc.json
**/*.map
**/*.ts
**/.vscode-test.*
webpack.config.*
.pytest_cache/**

# Hard coded ignore and unignore
node_modules/**
dist/**/node_modules/**
!node_modules/@img/**
!node_modules/sharp/install
!node_modules/sharp/lib
!node_modules/sharp/package.json
!node_modules/pdfjs-dist/**

# But, do NOT ignore the following required modules:
`;

  const ignoreRules = Array.from(allDependencies)
    .sort()
    .filter((depName) => ignoredDependencies.every((ignored) => !depName.startsWith(ignored)))
    .map((depName) => `!node_modules/${depName}/**`);

  const ignoreContent = ignoreHeader + ignoreRules.join('\n');

  const outputPath = path.join(__dirname, '.vscodeignore');
  fs.writeFileSync(outputPath, ignoreContent);

  console.log(`.vscodeignore has been successfully generated at: ${outputPath}`);
} catch (error) {
  console.error('Failed to generate .vscodeignore file.');
  console.error('Original error:', error);
  process.exit(1);
}
